import { defineStore } from 'pinia'
import { getMenuListApi } from '@/api/system/menu/menu'
import { RouteRecordRaw } from 'vue-router'
import Layout from '@/layout/Index.vue'
import { routerStore } from './router'
const modules = import.meta.glob('../views/**/*.vue')

// 定义state类型
export type MenuState = {
    count: number
    collapse: boolean
    smallCollapse: boolean
    screenIsBig: boolean
    menuList: any
}

// 定义store
export const menuStore = defineStore('menuStore', {
    state: (): MenuState => {
        return {
            count: 0,
            collapse: false,
            smallCollapse: true,
            screenIsBig: false,
            menuList: [
                {
                    path: '/dashboard',
                    component: () => import('@/layout/dashboard/Index.vue'),
                    name: 'dashboard',
                    meta: {
                        title: '首页',
                        icon: 'Buildings-home-4'
                    }
                }
            ]
        }
    },
    actions: {
        setCount(count: number) {
            this.count = count
        },
        setCollapse(collapse: boolean) {
            this.collapse = collapse
        },
        setSmallCollapse(collapse: boolean) {
            this.smallCollapse = collapse
            // console.log('this.smallCollapse=', this.smallCollapse)
        },
        setScreenIsBig(isBig: boolean) {
            this.screenIsBig = isBig
        },
        setMenuList(router: any) {
            return new Promise((resolve, reject) => {
                getMenuListApi()
                    .then((res) => {
                        let accessedRoutes, newMenuList
                        if (res.code == 200) {
                            const rStore = routerStore()
                            //动态生成路由
                            accessedRoutes = filterAsyncRoutes(
                                res.data.route_tree,
                                router,
                                rStore
                            )
                            console.log('路由: ', accessedRoutes)

                            newMenuList = fixLeftMenuList(
                                res.data.left_menu_tree
                            )
                            //设置menuList
                            this.menuList = this.menuList.concat(newMenuList)
                            // console.log('左侧菜单: ', this.menuList)
                        }
                        //返回
                        resolve(accessedRoutes)
                    })
                    .catch((error) => {
                        reject(error)
                    })
            })
        }
    },
    getters: {
        getCount(state) {
            return state.count
        },
        getCollapse(state) {
            return state.collapse
        },
        getSmallCollapse(state) {
            return state.smallCollapse
        },
        getScreenIsBig(state) {
            return state.screenIsBig
        },
        getMenuList(state) {
            return state.menuList
        }
    }
})

export function filterAsyncRoutes(
    routes: RouteRecordRaw[],
    router: any,
    rStore: any
) {
    // console.log('route_tree', routes)
    const res: Array<RouteRecordRaw> = []
    routes.forEach((route: any) => {
        const tmp = { ...route }
        const component = tmp.component
        if (route.component) {
            if (tmp.type == 0) {
                tmp.component = Layout
            } else {
                tmp.component = modules[`../views/${component}.vue`]
            }
        }
        if (tmp.children !== null) {
            //递归
            tmp.children = filterAsyncRoutes(tmp.children, router, rStore)
        }
        if (tmp.is_link == false) {
            rStore.setKeepAliveRouters(tmp.name, tmp.meta.keep_alive)
            router.addRoute(tmp)
            res.push(tmp)
        }
    })
    return res
}

// export function tempRouteToRoutes(
//     routes: RouteRecordRaw[],
//     tempRoute: RouteRecordRaw
// ) {
//     console.log('tempRoute=', tempRoute)

// }

export function fixTempRoutes(
    routes: RouteRecordRaw[],
    tempRoutes: RouteRecordRaw[],
    router: any
) {
    if (tempRoutes.length > 0) {
        tempRoutes.forEach((temp: any) => {
            routes.forEach((route: any) => {
                // console.log('tempRouteToRoutes route=', route)
                if (route.children != null && route.children.length > 0) {
                    route.children.forEach((rt: any) => {
                        // console.log('tempRouteToRoutes rt=', rt)
                        if (rt.id == temp.parent_id) {
                            router.addRoute(temp)
                            route.children.push(temp)
                        }
                    })
                }
            })
        })
    }
}

export function deepClone(data: any): any {
    // 获取传⼊拷贝函数的数据类型
    const type = typeof data
    // console.log('type: ', type)
    // 定义⼀个返回any类型的数据
    let reData: any
    // 递归遍历⼀个array类型数据，
    if (type === 'object') {
        if (data instanceof Array) {
            //递归遍历⼀个object类型数据
            reData = []
            for (const i in data) {
                reData[i] = deepClone(data[i])
            }
        } else {
            //递归遍历⼀个object类型数据
            reData = {}
            for (const i in data) {
                reData[i] = deepClone(data[i])
            }
        }
    } else {
        // 返回基本数据类型
        return data
    }
    // 将any类型的数据return出去，作为deepClone的结果
    return reData
}

export function fixLeftMenuList(menuList: any) {
    let newMenuList = deepClone(menuList)
    // console.log('newMenuList=', newMenuList)
    newMenuList.forEach((menu: any) => {
        // console.log('menu:', menu)
        if (menu.children.length > 0) {
            let i = -1
            let index = -1
            menu.children.forEach((m: any) => {
                // console.log('m:', m)
                i++
                if (m.hidden == true) {
                    index = i
                }
                if (m.children.length > 0) {
                    let j = -1
                    let jndex = -1
                    m.children.forEach((mm: any) => {
                        // console.log('mm: ', mm)
                        j++
                        if (mm.hidden == true) {
                            jndex = j
                        }
                    })
                    if (jndex > -1) {
                        m.children.splice(jndex, 1)
                    }
                }
            })
            if (index > -1) {
                // console.log('index===', index)
                menu.children.splice(index, 1)
            }
        }
    })
    // console.log('newMenuList=====', newMenuList)
    return newMenuList
}
